package com.wswy.wzcx.ui.main.common

import android.arch.lifecycle.Observer
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import com.che.libcommon.ui.BaseFragment
import com.wswy.wzcx.R
import com.wswy.wzcx.module.base.CBaseFragment
import com.wswy.wzcx.ui.fkdj.FinePaymentFragment
import com.wswy.wzcx.ui.fkdj.FinePreFragment
import com.wswy.wzcx.ui.fkdj.FineViewModel
import com.wswy.wzcx.utils.UiUtils

class HomeFKDJFragment : CBaseFragment() {

    private companion object {

    }
    private lateinit var fineViewModel: FineViewModel
    private var fragment: BaseFragment?=null

    private var preFragment: BaseFragment?=null

    override fun getContentLayoutId(): Int {
        return R.layout.fragment_home_fkdj
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        UiUtils.injectStatusBar(view)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        childFragmentManager.beginTransaction().replace(R.id.fl_content, FinePreFragment().apply {
            preFragment = this
        }).commitNow()

        fineViewModel = provideViewModelFromActivity(FineViewModel::class.java)
        fineViewModel.onCreate()

        fineViewModel.getCheckFineLiveData().observe(this, Observer {


            it?.run {

                if(isOk()){

                    childFragmentManager.beginTransaction().run {

                        preFragment?.let {
                            hide(it)
                        }

                        fragment = FinePaymentFragment()


                        fragment?.let {

                            if (!it.isAdded){
                                add(R.id.fl_content,it)
                            }

                            show(it)
                        }

                        commitNow()

                    }


                }

            }

        })

    }




    private fun handleBack():Boolean{
        if (fragment is FinePaymentFragment){

            childFragmentManager.beginTransaction().run {

                fragment?.let {
                    remove(it)
                }

                fragment = null

                preFragment?.let {
                    show(it)
                }

                commitNow()

            }

            return true
        }
        return false
    }


    override fun onBackPress(): Boolean {

        return handleBack()
    }

}